package org.xiaov.core.collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xiaov.core.bean.BeanHelper;
import org.xiaov.execption.XiaovUtilsException;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 有关map的帮助类
 * @author: xiaovcloud
 * @date: 2021/1/17 14:50
 */
public class MapHelper {

    private static final Logger log = LoggerFactory.getLogger(MapHelper.class);

    /**
     * 新建一个HashMap
     *
     * @param <k>
     * @param <v>
     * @return
     */
    public static <k, v> Map<k, v> newHashMap() {
        return new HashMap<>(16);
    }

    /**
     * 新建一个HashMap,并初始化Hash桶的大小
     *
     * @param <k>
     * @param <v>
     * @return
     */
    public static <k, v> Map<k, v> newHashMap(int size) {
        return new HashMap<>(size);
    }

    /**
     * 判断为空
     *
     * @param map
     * @return
     */
    public static <k, v> boolean isEmpty(Map<k, v> map) {
        return map.isEmpty();
    }

    /**
     * 判断不为空
     *
     * @param map
     * @return
     */
    public static <k, v> boolean isNotEmpty(Map<k, v> map) {
        return !map.isEmpty();
    }

    /**
     * 转换成Bean对象
     *
     * @param map
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T toBean(Map<String, Object> map, Class<T> clazz) throws Exception {
        T obj = clazz.getDeclaredConstructor().newInstance();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 属性名
                String propertyName = entry.getKey();
                // 属性值
                Object value = entry.getValue();
                String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                //获取和map的key匹配的属性名称
                Field field = getClassField(clazz, propertyName);
                if (field == null) {
                    continue;
                }
                Class<?> fieldTypeClass = field.getType();
                value = BeanHelper.convertValType(value, fieldTypeClass);
                try {
                    clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
                } catch (NoSuchMethodException e) {
                    log.error("Map解析到Bean异常");
                    throw new XiaovUtilsException("Map解析到Bean异常", e);
                }
            }
        }
        return obj;
    }

    /**
     * 根据给定对象类匹配对象中的特定字段
     *
     * @param clazz
     * @param fieldName
     * @return
     */
    private static <T> Field getClassField(Class<T> clazz, String fieldName) {
        if (Object.class.getName().equals(clazz.getName())) {
            return null;
        }
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        //如果该类还有父类，将父类对象中的字段也取出
        Class<?> superClass = clazz.getSuperclass();
        //递归获取
        if (superClass != null) {
            return getClassField(superClass, fieldName);
        }
        return null;
    }

    /**
     * 将map转化成list
     *
     * @param map
     * @return
     */
    public static <T> List<T> toList(Map<String, T> map) {
        List<T> result = new ArrayList<>();
        map.forEach((k, v) -> {
            result.add(v);
        });
        return result;
    }


}
